#include "saleschange.h"
#include "ui_saleschange.h"

saleschange::saleschange(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::saleschange)
{
    ui->setupUi(this);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//适应
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//适应
    ui->tableWidget->setFocusPolicy(Qt::NoFocus);
    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Fixed);//第二列“产品选择”宽度设置
    ui->tableWidget->setColumnWidth(1,100);
    RightClickMenu=new QMenu(ui->tableWidget);

    connect(ui->tableWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(RightClickSlot(QPoint)));
    connect(RightClickMenu,SIGNAL(triggered(QAction*)),this,SLOT(RightClickAddRow(QAction*)));
    connect(RightClickMenu,SIGNAL(triggered(QAction*)),this,SLOT(RightClickDeleteRow(QAction*)));

    //右键插入删除
    m_addAction=new QAction(QString::fromUtf8("插入"),this);
    m_deleteAction=new QAction(QString::fromUtf8("删除"),this);
    RightClickMenu->addAction(m_addAction);
    RightClickMenu->addAction(m_deleteAction);

    ui->comboBox_5->addItems(changeReason());
    ui->comboBox_5->setCurrentIndex(-1);
}

saleschange::~saleschange()
{
    delete ui;
}

void saleschange::SalesChoose()
{
   //选择客户
   connect(ui->pushButton_2, &QPushButton::clicked, this, &saleschange::on_pushButton_2_clicked);
}
QStringList  saleschange::changeReason()
{
    QStringList list;
    list <<"产品损坏" <<"质量问题" <<"发错商品"<<"其它";
    return list;
}
void saleschange::RowInit(QTableWidget *T,int index)
{
    T->insertRow(index); //在最后一行的后面插入一行

    //在插入的行中输入产品选择按钮从数据库获得产品数据
    QPushButton *choose_btn = new QPushButton();
    choose_btn->setObjectName("choose_btn" + QString::number(index));
    choose_btn->setProperty("type", "databaseBtn"); //数据库按钮样式

    QWidget *widget = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout();
    layout->setMargin(0);//一定要有
    layout->addWidget(choose_btn);
    layout->setAlignment(choose_btn, Qt::AlignCenter);//控件在布局中居中显示
    widget->setLayout(layout);

    T->setCellWidget(index, 0, widget);//放在表格第1列
    connect(choose_btn, &QPushButton::clicked, this, &saleschange::choose_btn_clicked);

    for(int i=0;i<T->columnCount();i++)
    {
        if(i==0)    //为按钮列
            continue;
        QTableWidgetItem *item = new QTableWidgetItem();
        T->setItem(index,i,item);
        T->item(index,i)->setTextAlignment(Qt::AlignCenter);
    }
    DetailIDGenerate(index);
}

void saleschange::RowDelete(QTableWidget *T,int index)
{
    if(index!=-1)
    {
        for(int i=0;i<T->columnCount();i++)
        {
            QWidget *widget=T->cellWidget(index,i);
            //确保不为空
            if(widget)
            {
                T->removeCellWidget(index,i);
                delete widget;  //释放
            }
        }
        T->removeRow(index);
    }
}

void saleschange::RightClickSlot(QPoint pos)
{
    QModelIndex index =ui->tableWidget->indexAt(pos);    //找到tableview当前位置信息
    tbwgt = ui->tableWidget;
    iPosRow = index.row();    //获取到了当前右键所选的行数
    if(index.isValid())        //如果行数有效，则显示菜单
    {
        RightClickMenu->exec(QCursor::pos());
    }

}

void saleschange::RightClickAddRow(QAction *act)
{
    if(act->text() == QString::fromUtf8("插入"))   //选中了插入这个菜单
    {
        if(tbwgt == ui->tableWidget){
            RowInit(tbwgt, iPosRow);
        }
//        else{
//            RowInit2(tbwgt,iPosRow);
//        }
    }
}

void saleschange::RightClickDeleteRow(QAction *act)
{
    if(act->text() == QString::fromUtf8("删除"))   //选中了删除这个菜单
    {
        RowDelete(ui->tableWidget,iPosRow);
    }
}

void saleschange::choose_btn_clicked()
{
    QPushButton* btn = qobject_cast<QPushButton*>(this->sender());
    if (btn == nullptr)
        return;

    // 获取按钮所在的行
    QModelIndex qIndex = ui->tableWidget->indexAt(QPoint(btn->parentWidget()->frameGeometry().x(), btn->parentWidget()->frameGeometry().y()));
    row = qIndex.row();

    //按钮状态选择
    if(btn->property("type")=="check")
    {
        btn->setProperty("type","checked");
        style()->polish(btn);
        vecItemIndex.push_back(row);//存储选中的行号
    }
    else if(btn->property("type")=="checked")
    {
        btn->setProperty("type","check");
        style()->polish(btn);
        vecItemIndex.erase(std::remove(vecItemIndex.begin(), vecItemIndex.end(), row), vecItemIndex.end()); //删除选中的行号
    }
    else if(btn->property("type")=="databaseBtn")
    {
        //创建数据选择子界面
        dc=new DataChoose();
        dc->setTitle("选择销售订单（详细编号）");
        dc->myModel->setQuery(QString("SELECT 销售订单详细编号, 产品名称, 产品属性, 产品编码, 销售数量, 销售单价, 售价合计 FROM 订单统计表 WHERE 销售订单编号 = '%1'").arg(ui->lineEdit_9->text()));
//        dc->myModel->setHeaderData(0,Qt::Horizontal,"销售订单详细编号");
//        dc->myModel->setHeaderData(1,Qt::Horizontal,"产品名称");
//        dc->myModel->setHeaderData(2,Qt::Horizontal,"产品属性");
//        dc->myModel->setHeaderData(3,Qt::Horizontal,"产品编码");
//        dc->myModel->setHeaderData(4,Qt::Horizontal,"销售数量");
//        dc->myModel->setHeaderData(5,Qt::Horizontal,"销售单价");
//        dc->myModel->setHeaderData(6,Qt::Horizontal,"售价合计");
        dc->show();
        //子界面向主界面传送选择的数据
        connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
                this, [this](const QModelIndexList& list)
        {
                //QTableWidgetItem *item = new QTableWidgetItem(list[0].data().toString());
                    ui->tableWidget->item(row,2)->setText(list[1].data().toString());
                    ui->tableWidget->item(row,3)->setText(list[2].data().toString());
                    ui->tableWidget->item(row,4)->setText(list[3].data().toString());
                    ui->tableWidget->item(row,5)->setText(list[4].data().toString());
                    ui->tableWidget->item(row,6)->setText(list[5].data().toString());
                    ui->tableWidget->item(row,7)->setText(list[6].data().toString());
                    changedProductTotal();

        });

    }

}


//销售产品明细表格中添加新行
void saleschange::on_add_btn_clicked()
{
    if(ui->add_btn->text()=="添加")
    {
        RowInit(ui->tableWidget,ui->tableWidget->rowCount());
    }
    else if(ui->add_btn->text()=="取消操作")
    {
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,0);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","databaseBtn");
                style()->polish(btn);
            }
        }

        ui->delete_btn->setText(QString::fromUtf8("删除"));
        ui->delete_btn->setProperty("type","deleteData");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("添加"));
        ui->add_btn->setProperty("type","addData");
        style()->polish(ui->add_btn);
    }

}

//表格中删除选中行
void saleschange::on_delete_btn_clicked()
{
    if(ui->delete_btn->text()=="删除")
    {
        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,0);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","check");
                style()->polish(btn);
            }
        }
        ui->delete_btn->setText(QString::fromUtf8("删除选中"));
        ui->delete_btn->setProperty("type","deleteConfirm");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("取消操作"));
        ui->add_btn->setProperty("type","deleteCancel");
        style()->polish(ui->add_btn);
    }

    else if(ui->delete_btn->text()=="删除选中")
    {
        sort(vecItemIndex.rbegin(), vecItemIndex.rend());
        for (unsigned int i = 0 ; i < vecItemIndex.size(); i++)
        {
            RowDelete(ui->tableWidget,vecItemIndex[i]);
        }
        vecItemIndex.clear();  //清空容器
        vecItemIndex.shrink_to_fit();   //将容器的容量缩减至和实际存储元素的个数相等，释放内存

        ui->delete_btn->setText(QString::fromUtf8("删除"));
        ui->delete_btn->setProperty("type","deleteData");
        style()->polish(ui->delete_btn);

        ui->add_btn->setText(QString::fromUtf8("添加"));
        ui->add_btn->setProperty("type","addData");
        style()->polish(ui->add_btn);

        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QWidget *widget=ui->tableWidget->cellWidget(i,0);
            if(widget)
            {
                QPushButton* btn = dynamic_cast<QPushButton*>(widget->layout()->itemAt(0)->widget());
                btn->setProperty("type","databaseBtn");
                style()->polish(btn);
            }
        }

    }

}

void saleschange::on_pushButton_2_clicked()
{
    dc=new DataChoose();
    dc->setTitle("选择订单");
    dc->myModel->setQuery(QString("SELECT DISTINCT 客户名称, 客户类别, 客户编码, 客户联系人姓名, 客户联系人手机, 销售员, 订单签订日期, 销售订单编号 From 订单统计表"));
    //QString("SELECT 销售订单详细编号, 产品名称, 产品属性, 产品编码, 销售数量, 销售单价, 售价合计 FROM 订单统计表 WHERE 销售订单编号 = '%1'").arg(ui->lineEdit_9->text())
    dc->show();
    connect(dc,static_cast<void(DataChoose::*)(const QModelIndexList&)>(&DataChoose::singal_selectedItems),
            this, [this](const QModelIndexList& list)
    {
                ui->lineEdit->setText(list[0].data().toString());
                ui->lineEdit_10->setText(list[1].data().toString());
                ui->lineEdit_2->setText(list[2].data().toString());
                ui->lineEdit_8->setText(list[3].data().toString());
                ui->lineEdit_7->setText(list[4].data().toString());
                ui->lineEdit_11->setText(list[5].data().toString());
                ui->lineEdit_12->setText(list[6].data().toString());
                ui->lineEdit_9->setText(list[7].data().toString());

    });
}

//换货单号生成
void saleschange::IDGenerate()
{
    if(ui->comboBox_2->currentIndex()==-1)
    {
        return;
    }
    else
    {
    QString time=ui->comboBox_2->dateToStr().remove(QChar('-'), Qt::CaseInsensitive),   //去除字符‘-’
            limit = "HHDD";

    limit += time;
    QSqlQuery query= mydb->SortData("换货统计表","换货单编号",false,"换货单编号",limit); //降序排列

    if(query.next())
    {
        QString str=query.value(10).toString();
        QString num=NumberIncrease(str.right(3)); //截取后3位,自增
        ui->lineEdit_13->setText(limit+"-"+num);
    }
    else
        ui->lineEdit_13->setText(limit+"-"+"001");
    }
}

// 换货详细单号生成
//eg: HHDD 20231023 001 01 , 17位
void saleschange::DetailIDGenerate(int index)
{
    if(ui->tableWidget->rowCount()==0 || ui->lineEdit_13->text()==nullptr)
        return;

    QString limit=ui->lineEdit_13->text();
    for(int i=index; i<ui->tableWidget->rowCount(); i++)
    {
        if(i==0)
            ui->tableWidget->item(i,1)->setText(limit+"-01");
        else
        {
            QString num=NumberIncrease(ui->tableWidget->item(i-1,1)->text().right(2)); //截取上一单元格后两位,自增
            ui->tableWidget->item(i,1)->setText(limit+"-"+num);
        }
    }
}

void saleschange::on_comboBox_2_editTextChanged(const QString &arg1)
{
    IDGenerate();
    DetailIDGenerate(0);
}
void saleschange::changedProductTotal()
{
    int total_num=0;
    int total_price=0;
    for(int i=0;i<ui->tableWidget->rowCount();i++)
    {
        total_num+=ui->tableWidget->item(i,5)->text().toInt();
        total_price+=ui->tableWidget->item(i,7)->text().toInt();
    }

    ui->lineEdit_5->setText(QString("%1").arg(total_num));
    ui->lineEdit_6->setText(QString("%1").arg(total_price));
}

//提交
void saleschange::on_pushButton_clicked()
{
        if(ui->lineEdit->text()==nullptr)
        {
            warning(this,"未选择销售订单");
            return;
        }
        if(ui->comboBox_2->currentText()==nullptr)
        {
            warning(this,"未选择换货日期");
            return;
        }

        if(ui->comboBox_5->currentIndex()==-1)
        {
            warning(this,"未选择换货原因");
            return;
        }
        if(ui->tableWidget->rowCount()==0)
        {
            warning(this,"未选择具体换货产品");
            return;
        }

    int ret = QMessageBox::question(this, "上传换货单","确认上传？", QMessageBox::Yes, QMessageBox::No);
    if(ret == QMessageBox::Yes)
    {

        for(int i=0;i<ui->tableWidget->rowCount();i++)
        {
            QSqlQuery query;
            //插入 订单详细信息表

            query.prepare(QString("INSERT INTO 换货统计表(客户名称,客户类别,客户编码,客户联系人姓名,客户联系人手机,销售员,订单签订日期,换货申请日期,销售订单编号,换货单编号,"
                                  "换货原因,换货产品总数,换货产品售价总额,"
                                  "换货单详细编号,产品名称,产品属性,产品编码,销售数量,销售单价,售价合计)"
                                " VALUES ('%1','%2','%3','%4','%5','%6','%7','%8','%9','%10',"
                                  "'%11','%12','%13',"
                                  "'%14','%15','%16','%17','%18','%19','%20');")
                          .arg(ui->lineEdit->text()).arg(ui->lineEdit_10->text()).arg(ui->lineEdit_2->text()).arg(ui->lineEdit_8->text()).arg(ui->lineEdit_7->text()).arg(ui->lineEdit_11->text()).arg(ui->lineEdit_12->text())
                          .arg(ui->comboBox_2->currentText()).arg(ui->lineEdit_9->text()).arg(ui->lineEdit_13->text()).arg(ui->comboBox_5->currentText()).arg(ui->lineEdit_5->text()).arg(ui->lineEdit_6->text())
                          .arg(ui->tableWidget->item(i,1)->text()).arg(ui->tableWidget->item(i,2)->text()).arg(ui->tableWidget->item(i,3)->text()).arg(ui->tableWidget->item(i,4)->text()).arg(ui->tableWidget->item(i,5)->text())
                          .arg(ui->tableWidget->item(i,6)->text()).arg(ui->tableWidget->item(i,7)->text()));

            if(!query.exec())
            {
                qDebug()<<query.lastError();
                warning(this,"上传失败");
                return;
            }
            query.clear();  //清空sql语句
         }
        QMessageBox::information(this, "上传换货单","上传成功");
        this->clear();
    }
}


void saleschange::clear()
{
    ui->lineEdit->setText("");
    ui->lineEdit_2->setText("");
    ui->lineEdit_5->setText("");
    ui->lineEdit_6->setText("");
    ui->lineEdit_8->setText("");
    ui->lineEdit_7->setText("");
    ui->lineEdit_9->setText("");
    ui->lineEdit_10->setText("");
    ui->lineEdit_11->setText("");
    ui->lineEdit_12->setText("");
    ui->lineEdit_13->setText("");
    ui->comboBox_2->setEditText("");
    ui->comboBox_5->setCurrentIndex(-1);

    for(int i = ui->tableWidget->rowCount()-1; i>=0 ; i--)
    {
        RowDelete(ui->tableWidget,i);
    }
}
